﻿@using Xms.Schema.Extensions;

@model Xms.Web.Models.SelectEntityRecordsDialogModel
@{
    Layout = null;
}

@{
    var mainEntity = Model.EntityList.First();
    var __ModalGuid = Guid.NewGuid().ToString().Replace("-", "");
    DialogModel dialogModel = ViewData["DialogModel"] as DialogModel;
}

<link rel="stylesheet" href="/content/js/jqgird/css/ui.jqgrid-bootstrap.css?v=@app.PlatformSettings.VersionNumber">
<link rel="stylesheet" href="/content/js/jqgird/plugins/bootstrap-datepicker.min.css?v=@app.PlatformSettings.VersionNumber">
<!-- （Modal） -->
<div class="modal fade in" id="entityRecordsModal" tabindex="-1" role="dialog"
     aria-labelledby="entityRecordsModalLabel" style="display:block;" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">
                    ×
                </button>
                <h4 class="modal-title" id="entityRecordsModalLabel">
                    <span class="glyphicon glyphicon-th"></span> @mainEntity.LocalizedName - @Model.QueryView.Name - @app.T["queryview"]
                </h4>
            </div>
            <div class="modal-body">
                <div id="queryview-section">
                    <div class="container-fluid">
                        <form id="searchForm" action="/entity/RecordsDialog" onkeydown="if(event.keyCode==13)return false;" method="post" class="form-horizontal">
                            @Html.HiddenFor(x => x.EntityId)
                            @Html.HiddenFor(x => x.QueryId, new { id = "SelectEntityRecordsQueryId" })
                            @Html.HiddenFor(x => x.SortBy)
                            @Html.HiddenFor(x => x.SortDirection)
                            <input type="hidden" value="1" name="page" />
                            <input type="hidden" name="QField" id="QField" value="@Model.QField" />
                            <input type="hidden" name="mutilChecker" id="mutilChecker" value="" />
                            <div class="form-group">
                                <div class="col-sm-2">
                                    <a id="fieldDropdown" class="dropdown-toggle btn btn-link btn-sm" data-toggle="dropdown" href="#">
                                        <span>@app.T["search_allfield"]</span> <span class="caret"></span>
                                    </a>
                                    <ul class="dropdown-menu">
                                        <li><a href="javascript:void(0)" data-name="">@app.T["search_allfield"]</a></li>
                                        @foreach (var cell in Model.Grid.Rows[0].Cells)
                                        {
                                            var isrelated = cell.Name.IndexOf(".") > 0;
                                            var k = isrelated ? cell.Name.Split('.')[1] : cell.Name.ToLower();
                                            var label = cell.Label;
                                            Xms.Schema.Domain.Attribute attr = null;
                                            if (!isrelated)
                                            {
                                                attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(k));
                                                //label = attr.LocalizedName;
                                            }
                                            else
                                            {
                                                attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(k));
                                                //显示字段+引用字段
                                                //var relationship = Model.RelationShipList.Find(n => n.Name.IsCaseInsensitiveEqual(cell.Name.Split('.')[0]));
                                                //label = attr.LocalizedName + "(" + relationship.ReferencingAttributeLocalizedName + ")";
                                            }
                                            if (attr == null || attr.TypeIsDateTime()) { continue; }
                                            <li><a href="javascript:void(0)" data-name="@cell.Name.ToLower()" data-type="@attr.AttributeTypeName">@cell.Label</a></li>
                                        }
                                    </ul>
                                </div>
                                <div class=" col-sm-4" style="width:282px;">
                                    <div class="input-group input-group-sm">
                                        @Html.TextBoxFor(x => x.Q, new { @class = "form-control", @style = "width:200px;", @placeholder = app.T["search_quickly"] })
                                        <span class="input-group-btn">
                                            <button class="btn btn-default" type="button" name="clearBtn">
                                                <span class="glyphicon glyphicon-remove-sign"></span>
                                            </button>
                                            <button class="btn btn-default" type="button" name="searchBtn">
                                                <span class="glyphicon glyphicon-search"></span>
                                            </button>
                                        </span>
                                    </div>
                                </div>
                                <div class="input-group input-group-sm col-sm-3" id="filterSearcher">
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="panel panel-default " id="gridview" style="margin-bottom:0;">
                        <div class="table-responsive" style="min-height:300px;max-height:350px;">
                            <table class="table table-hover table-striped table-condensed datatable" id="" data-pageurl="@app.Url" data-ajax="true" data-ajaxcontainer="gridview" data-ajaxcallback="EntityRecordsModel@(__ModalGuid).ajaxgrid_reset()" data-sortby="@Model.SortBy.ToLower()" data-sortdirection="@Model.SortDirection" data-singlemode="@dialogModel.SingleMode" style="table-layout:fixed;">
                                <thead>
                                    <tr>
                                        <th width="22"><input type="checkbox" name="checkall" /></th>
                                        <th width="35"></th>
                                        @foreach (var cell in Model.Grid.Rows[0].Cells)
                                        {
                                            var isrelated = cell.Name.IndexOf(".") > 0;
                                            var k = isrelated ? cell.Name.Split('.')[1] : cell.Name.ToLower();
                                            var label = cell.Label;
                                            var itemStr = "";
                                            Xms.Schema.Domain.Attribute attr = null;
                                            if (!isrelated)
                                            {
                                                attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(k));
                                                //label = attr.LocalizedName;
                                            }
                                            else
                                            {
                                                attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(k));
                                                //显示字段+引用字段
                                                //var relationship = Model.RelationShipList.Find(n => n.Name.IsCaseInsensitiveEqual(cell.Name.Split('.')[0]));
                                                //label = attr.LocalizedName + "(" + relationship.ReferencingAttributeLocalizedName + ")";
                                            }
                                            if (attr == null) { continue; }

                                            if (attr.TypeIsPickList() || attr.TypeIsBit() || attr.TypeIsStatus() || attr.TypeIsState())
                                            {
                                                itemStr = (attr.TypeIsPickList() || attr.TypeIsStatus()) ? attr.OptionSet.Items.SerializeToJson() : attr.PickLists.SerializeToJson();
                                            }
                                            <th data-name="@cell.Name.ToLower()" style="width:@(cell.Width+"px")" data-label="@cell.Label" data-type="@attr.AttributeTypeName" data-opts='@Html.UrlEncoder.Encode(itemStr)' data-entityid="@attr.ReferencedEntityId" data-referencedentityid="@attr.ReferencedEntityId">
                                            </th>
                                        }
                                    </tr>
                                </thead>
                                <tbody>
                                    @{
                                        var primaryKey = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.TypeIsPrimaryKey());
                                        var primaryField = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.IsPrimaryField == true);
                                    }
                                    @foreach (var item in Model.Items)
                                    {
                                        var lines = (item as IDictionary<string, object>).ToList();
                                        var id = lines.Find(n => n.Key.IsCaseInsensitiveEqual(primaryKey.Name)).Value;
                                        var name = lines.Find(n => n.Key.IsCaseInsensitiveEqual(primaryField.Name)).Value;
                                        <tr data-dbclick="EntityRecordsModel@(__ModalGuid).selectedrow('@id')" data-id="@id">
                                            <td>
                                                <input type="checkbox" name="recordid" value="@id" />
                                            </td>
                                            <td>
                                                <input type="hidden" name="recordname" value="@name" />
                                                <a class="btn btn-link btn-xs selectBtn"><span class="glyphicon glyphicon-ok"></span></a>
                                            </td>
                                            @foreach (var cell in Model.Grid.Rows[0].Cells)
                                            {
                                                var columnName = cell.Name.ToLower();
                                                var isrelated = columnName.IndexOf(".") > 0;
                                                var attrName = isrelated ? columnName.Split('.')[1] : columnName;
                                                Xms.Schema.Domain.Attribute attr = null;
                                                if (isrelated)
                                                {
                                                    attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(attrName));
                                                }
                                                else
                                                {
                                                    attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(attrName));
                                                }
                                                if (attr == null)
                                                {
                                                    continue;
                                                }
                                                if (attr.TypeIsPrimaryKey() || attr.TypeIsLookUp() || attr.TypeIsOwner())
                                                {
                                                    columnName = attr.TypeIsPrimaryKey() ? primaryField.Name : columnName += "Name";
                                                    var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value;
                                                    var recordid = lines.Find(n => n.Key.IsCaseInsensitiveEqual(cell.Name)).Value;
                                                    <td>
                                                        @if (attr.TypeIsPrimaryKey() || attr.DisplayStyle == "link")
                                                        {
                                                            <a href="@("/"+app.OrganizationUniqueName)/entity/edit?entityid=@attr.ReferencedEntityId&recordid=@recordid" target="_blank" title=""> @value </a>
                                                        }
                                                        else
                                                        {
                                                            @value
                                                        }
                                                    </td>
                                                }
                                                else if (attr.TypeIsPickList() || attr.TypeIsBit() || attr.TypeIsState() || attr.TypeIsStatus())
                                                {
                                                    columnName += "Name";
                                                    var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value;
                                                    <td> @value </td>
                                                }
                                                else
                                                {
                                                    var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value;
                                                    if (value != null && (attr.TypeIsDecimal()
                                                                    || attr.TypeIsFloat()))
                                                    {
                                                        value = string.Format("{0:N2}", value);
                                                    }
                                                    else if (value != null && attr.TypeIsMoney())
                                                    {
                                                        value = string.Format("￥{0:N2}", value);
                                                    }
                                                    else if (value != null && attr.TypeIsDateTime())
                                                    {
                                                        if (attr.DataFormat == "yyyy/MM/dd")
                                                        {
                                                            value = DateTime.Parse(value + "").ToString("yyyy/MM/dd");
                                                        }
                                                        value = string.Format("{0:G}", value);
                                                    }
                                                    else if (attr.IsPrimaryField)
                                                    {
                                                        value = string.Format("<a href=\"/" + app.OrganizationUniqueName + "/entity/create?entityid={0}&recordid={1}\" target=\"_blank\">{2}</a>", mainEntity.EntityId, id, value);
                                                    }
                                                    <td>@Html.Raw(value)</td>
                                                }
                                            }
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                        <div class="panel-footer">
                            <div class="row">
                                <div class="col-sm-4">
                                    @(app.T["pagination_label"].Replace("{page}", Model.Page.ToString()).Replace("{totalpages}", Model.TotalPages.ToString()).Replace("{totalitems}", Model.TotalItems.ToString()))
                                </div>
                                <div id="page-selection" class="col-sm-8 page-selection" data-total="@Model.TotalPages" data-page="@Model.Page"></div>
                            </div>
                        </div>
                    </div>
                    <div class="selectEntityRecords-datagrid"></div>
                </div>
                <script src="/content/js/jquery.bootpag.min.js?v=@app.PlatformSettings.VersionNumber"></script>
                <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script>
                <script src="/content/js/bootstrap-datepicker-1.5.0/js/bootstrap-datepicker.min.js?v=@app.PlatformSettings.VersionNumber"></script>
                <script src="/content/js/bootstrap-datepicker-1.5.0/locales/bootstrap-datepicker.zh-CN.min.js?v=@app.PlatformSettings.VersionNumber" charset="UTF-8"></script>
                <script src="~/content/js/fetch.js?v=@app.PlatformSettings.VersionNumber"></script>
                @{await Html.RenderPartialAsync("FetchLabel"); }
                <script>
                ;(function () {
                    var MODAL_GUID = '@Html.Raw(__ModalGuid)';
                    var EntityRecordsModel = {
                        dialogid: '#entityRecordsModal',
                        dialog: $('#entityRecordsModal'),
                        datatable: $('#entityRecordsModal .datatable'),
                        pageUrl: $("#entityRecordsModal .datatable").attr('data-pageurl'),
                        queryid: '@Html.Raw(Model.QueryId)',
                        entityid: '@Html.Raw(Model.EntityId)',
                        cacheFilters:new Xms.Fetch.FilterExpression(),
                        filters: @Html.Raw(Model.Filter.SerializeToJson()),
                        sortby: '@Model.SortBy',
                        sortdir: '@Model.SortDirection',
                        q: '@Model.Q',
                        qfield: '@Model.QField',
                        page: @Model.Page,
                        currentUrl:'',
                        callback:@Html.Raw(dialogModel.CallBack),
                        inputid:'@Html.Raw(dialogModel.InputId)',
                        singlemode: @(dialogModel.SingleMode?"true":"false"),
                        checkedList:[],
                        ajaxTable : function () {
                            var self = $('#entityRecordsModal .datatable');
                            var containerId = '#' + self.attr('data-ajaxcontainer');
                            $(EntityRecordsModel.dialogid + " " + containerId).parent().delegate('a[data-ajax="true"]', 'click', function () {
                                var url = $(this).attr('href');
                                url = url + (url.indexOf('?') == -1 ? '?' : '&') + '__r=' + new Date().getTime();
                                //EntityRecordsModel.pageUrl = url;
                                $("#entityRecordsModal .datatable").attr('data-pageurl',url);
                                EntityRecordsModel.rebind(url);
                                return false;
                            });
                        },
                        ajaxgrid_reset : function () {
                            var self = $('#entityRecordsModal .datatable');
                            EntityRecordsModel.pageUrl = EntityRecordsModel.datatable.attr('data-pageurl');
                            EntityRecordsModel.pag_init();
                            var $inputid = $('#'+EntityRecordsModel.inputid);
                            var $mutilChecker = $('#mutilChecker')
                            if(!EntityRecordsModel.singlemode && $inputid.length>0 && $inputid.val()!=='' && $inputid.attr('data-value') && $inputid.attr('data-value')!=""){
                                try{
                                    var checklist = $inputid.attr('data-value').split(',');
                                    var checknamelist = $inputid.val().split(',');
                                    var _res = [];
                                    $.each(checklist,function(key,item){
                                        var tempobj = {
                                            id:item,
                                            name:checknamelist[key]
                                        }
                                        _res.push(tempobj);
                                    });
                                    $mutilChecker.val(encodeURIComponent(JSON.stringify(_res)));
                                }catch(e){
                                    console.log(e);
                                }
                            }

                            Xms.Web.DataTable(self,{
                                changeHandler:function(obj,type,target){
                                    if(type=='item'){
                                        var $obj = null
                                        if($(obj).find('input[name="recordid"]').length==0){
                                            $obj = $(obj);
                                        }else{
                                            $obj = $(obj).find('input[name="recordid"]');
                                        }
                                        var _check = $obj.prop('checked');
                                        if(_check){
                                            EntityRecordsModel._addRowInHidden();
                                        }else{
                                            EntityRecordsModel._removeRowByHidden($obj.val());
                                        }
                                    }else{

                                        var _check = $(obj).prop('checked');
                                        if(_check){
                                            EntityRecordsModel._addRowInHidden();
                                        }else{
                                            EntityRecordsModel.datatable.find('tbody').find('input[name="recordid"]').each(function(){

                                                EntityRecordsModel._removeRowByHidden($(this).val());

                                            });
                                        }

                                    }
                                    console.log('changeHandler',_check)
                                }
                            });
                            console.log('pageclick');
                            if(EntityRecordsModel.singlemode==false){

                                console.log('tr.click.binding');
                                EntityRecordsModel.dialog.find(".datatable tbody tr").off('tr.click').on('tr.click',function(e,data){
                                    var $self = $(this);
                                    var id = $(this).find('input[name=recordid]').val();
                                    console.log('tr.click.trigger',data);
                                    if(data.flag){
                                        if(id){
                                            //console.log('tr.click._removeRowByHidden',id);
                                           // EntityRecordsModel._removeRowByHidden(id);
                                            console.log('remove');
                                        }
                                    }else{
                                        console.log('add');
                                      //  EntityRecordsModel._addRowInHidden();
                                    }
                                });
                                EntityRecordsModel._changepageChecked();
                            }
                            //EntityRecordsModel.ajaxTable();
                            //EntityRecordsModel.datatable.find('tbody>tr').each(function(i, n){
                            //    $(n).bind('dbclick', function(e){alert('abc');
                            //        Xms.Web.SelectingRow(this);
                            //        EntityRecordsModel.dialog_return();
                            //    });
                            //});
                            EntityRecordsModel._changepageChecked();
                        },
                        _changepageChecked:function(){
                            var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();
                            if(checkedData!=''){
                                checkedData = JSON.parse(decodeURIComponent(checkedData));
                            }
                            console.log('checkedData',checkedData);
                            if(checkedData && checkedData.length>0){
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]").each(function (i, n) {
                                    var flag = false;
                                    $.each(checkedData,function(ii,nn){
                                        if(nn.id == $(n).val()){//如果有重复的就不加进去
                                            flag = true;
                                        }
                                    });
                                    if(flag==true){
                                        $(this).prop('checked',true);
                                    }
                                });
                            }
                        },
                        _removeRowByHidden:function(id){
                            var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();
                            var checkedData1= null;
                            if($mutilChecker.val()!=''){
                                checkedData1 = JSON.parse(decodeURIComponent($mutilChecker.val()));
                            }

                            if(checkedData1){
                                var delIndex = null;
                                $.each(checkedData1,function(ii,nn){
                                    if(nn.id == id){//如果有重复的就不加进去
                                        delIndex = ii;
                                        return false;
                                    }
                                });
                                if(~delIndex){
                                    checkedData1.splice(delIndex,1);
                                    console.log('checkedData1',checkedData1);
                                    if(checkedData1.length==0){
                                        $mutilChecker.val('');
                                    }else{
                                        $mutilChecker.val(encodeURIComponent(JSON.stringify(checkedData1)));
                                    }
                                }
                            }
                        },
                        _addRowInHidden:function(){
                            var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();

                            if(checkedData!=''){
                                checkedData = JSON.parse(decodeURIComponent(checkedData));
                            }

                            if(checkedData && checkedData.length>0){
                                //防止添加重复的数据
                                var result = [];
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) {
                                    var flag = false;
                                    $.each(checkedData,function(ii,nn){
                                        if(nn.id == $(n).val()){//如果有重复的就不加进去
                                            flag = true;
                                        }
                                    });
                                    if(flag==false){
                                        var obj = new Object();
                                        obj.id = $(n).val();
                                        obj.name = $(n).parents('tr:first').find('input[name=recordname]').val();
                                        result.push(obj);
                                    }
                                });
                                checkedData = checkedData.concat(result);
                            }else{
                                var result = [];
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) {
                                    var obj = new Object();
                                    obj.id = $(n).val();
                                    obj.name = $(n).parents('tr:first').find('input[name=recordname]').val();
                                    result.push(obj);
                                });
                                checkedData = result;
                            }
                            console.log('checkedData',checkedData)
                            $mutilChecker.val(encodeURIComponent(JSON.stringify(checkedData)));
                        },
                        _emptyCheckerValue:function(){
                            var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();
                            $mutilChecker.val('');
                        },
                        pag_init : function () {

                            var a = $(EntityRecordsModel.dialogid + ' .page-selection');
                            var pageSetting = {
                                total: a.attr('data-total')
                                , maxVisible: 5
                                , page: a.attr('data-page')
                                , leaps: false
                                , prev: '&lsaquo;'
                                , next: '&rsaquo;'
                                , firstLastUse: true
                                , first: '&laquo;'
                                , last: '&raquo;'
                            };
                            $(EntityRecordsModel.dialogid + ' .page-selection').bootpag(pageSetting).on("page", function (event, /* page number here */ num) {
                                event.preventDefault();
                                EntityRecordsModel.page = num;
                                console.log('$("#entityRecordsModal .datatable")',$("#entityRecordsModal .datatable").attr('data-pageurl'));
                                EntityRecordsModel.rebind($("#entityRecordsModal .datatable").attr('data-pageurl'));
                                return false;
                            });
                        },
                        rebind: function (url,filters) {
                            var url = url || '/entity/RecordsDialog';
                            url = url + (url.indexOf('?') == -1 ? '?' : '&') + '__r=' + new Date().getTime();
                            var model = new Object();
                            model.EntityId = EntityRecordsModel.entityid;
                            model.QueryId = EntityRecordsModel.queryid;
                            if(EntityRecordsModel.cacheFilters && EntityRecordsModel.cacheFilters.Filters && EntityRecordsModel.cacheFilters.Filters.length>0){
                                var __filter =  new Xms.Fetch.FilterExpression();
                                __filter.Filters.push(EntityRecordsModel.filters);
                                var filters = EntityRecordsModel.cacheFilters;
                                $.each(filters.Filters,function(key,filter){
                                    if (filter.Conditions[0]
                                        && typeof filter.Conditions[0].Values === "object" && filter.Conditions[0].Values.length
                                        && filter.Conditions[0].Values[0].replace("\s", "") != ""
                                        || (filter.Conditions[0] && filter.Conditions[0].Values && filter.Conditions[0].Values.length>0 && filter.Conditions[0].Values[1] && filter.Conditions[0].Values[1].replace("\s", "") != "")
                                        ) {
                                        __filter.Filters.push(this);
                                    }

                                });
                                model.Filter = __filter;
                            }else{
                                model.Filter = filters || EntityRecordsModel.filters;
                            }
                            model.Q = $.getUrlParam("q", url) || EntityRecordsModel.q;
                            model.QField = $.getUrlParam("qfield", url) || EntityRecordsModel.qfield;
                            model.SortBy = $.getUrlParam("sortby", url)|| EntityRecordsModel.sortby;
                            model.SortDirection = $.getUrlParam("sortdirection", url) || EntityRecordsModel.sortdir;
                            model.InputId = $.getUrlParam("inputid", url) || EntityRecordsModel.inputid;
                            model.CallBack = $.getUrlParam("callback", url) || EntityRecordsModel.callback;
                            model.Page = $.getUrlParam("page", url) || EntityRecordsModel.page;
                            model.SingleMode = EntityRecordsModel.singlemode;
                            model.OnlyEnabledRecords = false;
                            console.log('rebind.model',model);

                            //在多选方式下，把之前页面的数据保存起来
                            if(model.SingleMode==false){

                            }
                            //在多选方式下，把之前页面的数据保存起来-----end
                            Xms.Web.LoadPage(url, model, function (response) {
                                $(EntityRecordsModel.dialogid + ' #gridview' ).html($(response).find('#gridview').html());
                                EntityRecordsModel.ajaxgrid_reset();
                            },null,null,true);
                        },
                        getNum_String: function(s){
                            return s.replace(/[^0-9]/ig,"")
                        },
                        selectedrow: function(id){
                            EntityRecordsModel.dialog.find('tr[data-id="'+id+'"]').find('.selectBtn').trigger('click');
                        },
                        dialog_return : function (obj) {
                            var result = new Array();
                            if(!obj){
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) {
                                    var obj = new Object();
                                    obj.id = $(n).val();
                                    obj.name = $(n).parents('tr:first').find('input[name=recordname]').val();
                                    result.push(obj);
                                });
                            }else{//防止多选时，始终是传回第一个已勾选上的值
                                var partr = $(obj).parents('tr:first');
                                var partrDom = partr.get(0);
                                var partrobj = {
                                    id:partr.find("input[name=recordid]").val(),
                                    name:partr.find('input[name=recordname]').val()
                                }
                                result.push(partrobj);
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) {
                                    if($(n).parents('tr:first').get(0)==partrDom){return true;}
                                    var obj = new Object();
                                    obj.id = $(n).val();
                                    obj.name = $(n).parents('tr:first').find('input[name=recordname]').val();
                                    result.push(obj);
                                });
                            }

                            if(EntityRecordsModel.singlemode==false){
                                var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();
                                if(checkedData!=''){
                                    checkedData = JSON.parse(decodeURIComponent(checkedData));
                                    result = checkedData;
                                }
                            }
                            if(result.length == 0){
                                Xms.Web.Alert(false, LOC_NOTSPECIFIED_RECORD);
                                return;
                            }
                            var dialog = $(EntityRecordsModel.dialogid);
                            console.log(result, EntityRecordsModel.inputid, dialog.data().OpenDialogCallback);
                            if (dialog.data().OpenDialogCallback) {
                                dialog.data().OpenDialogCallback(result, EntityRecordsModel.inputid)
                            } else {
                                EntityRecordsModel.callback && EntityRecordsModel.callback(result, EntityRecordsModel.inputid);
                            }

                            if($("#"+EntityRecordsModel.inputid).length>0){
                                $("#"+EntityRecordsModel.inputid).trigger("dialog.return",result);
                            }
                            //Xms.Web.Event.publish({result:result, inputid: EntityRecordsModel.inputid});
                            EntityRecordsModel.dialog.modal('hide');
                            //Xms.Web.CloseDialog('#entityRecordsModal');
                        },
                        CreateRecord: function () {
                            var url = '/entity/create?entityid=' + EntityRecordsModel.entityid;
                            Xms.Web.OpenWindow(ORG_SERVERURL+url);
                        }
                        ,enterSearch :function(e){
                            console.log(e);
                            e = e || window.event;
                            if(e.preventDefault){
                                e.preventDefault();
                            }else{
                                e.returnValue = false;
                            }
                            EntityRecordsModel.page = 1;
                            EntityRecordsModel.q = $(EntityRecordsModel.dialogid + ' #Q').val();
                            EntityRecordsModel.qfield = $(EntityRecordsModel.dialogid + ' #QField').val();
                            EntityRecordsModel.rebind();
                        }
                    };
                    $(function () {
                        EntityRecordsModel.ajaxTable();
                        EntityRecordsModel.ajaxgrid_reset();
                       // EntityRecordsModel.rebind(EntityRecordsModel.pageUrl);
                        //默认第一列为快速查找字段
                        //$(EntityRecordsModel.dialogid+' #fieldDropdown').next().find('a:eq(1)').trigger('click');
                        EntityRecordsModel.dialog.modal({
                            backdrop:'static'
                        });
                        EntityRecordsModel.dialog.on('hidden.bs.modal', function () {
                            Xms.Web.CloseDialog(EntityRecordsModel.dialogid);
                        });
                        $(EntityRecordsModel.dialogid + ' button[name=clearBtn]').off('click').on('click',null,function(e){
                            $(EntityRecordsModel.dialogid + ' #Q').val('');
                            EntityRecordsModel.q = '';
                            EntityRecordsModel.cacheFilters = new Xms.Fetch.FilterExpression();
                            EntityRecordsModel.rebind();
                            EntityRecordsModel._emptyCheckerValue();
                        });
                        $(EntityRecordsModel.dialogid + ' button[name=searchBtn]').off('click').on('click',null,function(e){
                            EntityRecordsModel.enterSearch(e);
                        });
                        $(EntityRecordsModel.dialogid + ' button[name=createBtn]').off('click').on('click',null,function(e){
                            EntityRecordsModel.CreateRecord();
                        });
                        $(EntityRecordsModel.dialogid + ' button[name=deleteBtn]').off('click').on('click',null,function(e){
                            EntityRecordsModel.DeleteRecord();
                        });
                        $(EntityRecordsModel.dialogid + ' .dropdown-menu').on('click','>li>a',function(e){
                            $(EntityRecordsModel.dialogid + ' #QField').val($(this).attr('data-name'))
                            $(EntityRecordsModel.dialogid + ' #fieldDropdown').find('span:first').text($(this).text());
                        });
                        $('body').off('click.selectentitydialog').on('click.selectentitydialog',EntityRecordsModel.dialogid + ' .selectBtn',function(e){
                            Xms.Web.SelectingRow(this);
                            EntityRecordsModel.dialog_return(this);
                        });

                        $(EntityRecordsModel.dialogid + " button[name='returnBtn']").click( function() {
                            EntityRecordsModel.dialog_return();
                        });
                        $(EntityRecordsModel.dialogid + " #Q").off('keydown.enter').on('keydown.enter', function(e) {
                            e = e || window.event;
                            if(e.keyCode==13){
                                EntityRecordsModel.enterSearch(e);
                            }
                        });

                        $('#filterSearcher').tableFiler({
                            table:$('#entityRecordsModal .datatable')
                            ,styles:"customer-filter-style"
                            ,clear:function(pluger,filters){
                                EntityRecordsModel.cacheFilters = new Xms.Fetch.FilterExpression();
                                EntityRecordsModel.rebind(null);
                            }
                            ,confirm:function(pluger,filters){
                            //if(EntityRecordsModel.filters.conditions.length>1){
                           //     EntityRecordsModel.filters.conditions = EntityRecordsModel.filters.conditions.slice(0,1);
                            // }
                                var _filter = new Xms.Fetch.FilterExpression();
                                $.each(filters,function(key,filter){
                                    if (filter.Conditions[0]
                                        && typeof filter.Conditions[0].Values === "object" && filter.Conditions[0].Values.length
                                        && filter.Conditions[0].Values[0].replace("\s", "") != ""
                                        || (filter.Conditions[0] && filter.Conditions[0].Values && filter.Conditions[0].Values.length>0 && filter.Conditions[0].Values[1] && filter.Conditions[0].Values[1].replace("\s", "") != "")
                                        ) {
                                        _filter.Filters.push(this);
                                    }

                                });
                                EntityRecordsModel.cacheFilters = _filter;
                                EntityRecordsModel.rebind();
                            }
                         });
                        console.log($('.selectEntityRecords-datagrid'))
                        //$('.selectEntityRecords-datagrid').cDatagrid({
                        //    entityid: EntityRecordsModel.entityid,
                        //    queryid: EntityRecordsModel.queryId,
                        //    pageModel: { type: "remote", rPP: 10, page: 1, strRpp: "{0}" },
                        //    columnFilter: function (items) {
                        //        console.log(items)
                        //        $.each(items, function (key, item) {
                        //            item.editable = false;

                        //        });
                        //        return items;
                        //    }
                        //});

                    });

                    window["EntityRecordsModel"+MODAL_GUID] = EntityRecordsModel;
                   })();
                </script>
            </div>
            <div class="modal-footer">
                <div class="pull-left">
                    <button type="button" class="btn btn-link" name="createBtn">
                        <span class="glyphicon glyphicon-plus-sign"></span> @app.T["add"]
                    </button>
                </div>
                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                    <span class="glyphicon glyphicon-remove"></span> @app.T["dialog_close"]
                </button>
                <button type="button" class="btn btn-primary" name="returnBtn">
                    <span class="glyphicon glyphicon-ok"></span> @app.T["dialog_ok"]
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->